package rsa

import (
	"encoding/json"
	"fmt"
	"gitee.com/binny_w/gin_starter/core"
	"math"
	"time"
)

type EncryptedData struct {
	D string `json:"d"`
	T int64  `json:"t"`
	S string `json:"s"`
}

func Decode(s string) (string, error) {
	r, err := instance.DecodeWithPrivateKey(s)
	if err != nil {
		return "", err
	}
	var in EncryptedData
	if err = json.Unmarshal([]byte(r), &in); err != nil {
		return "", err
	}
	n := time.Now().UnixMilli()
	if math.Abs(float64(in.T-n)) > 5000 {
		return "", fmt.Errorf("数据过期: %d - %d", n, in.T)
	}
	if len(in.S) != 8 {
		return "", fmt.Errorf("8位随机码错误: %s", in.S)
	}
	if bln, err := core.RedisVerify.Set(fmt.Sprintf("rsa_rand:%s", in.S), 1, 10*time.Second, "NX"); err != nil {
		return "", err
	} else if !bln {
		return "", fmt.Errorf("8位随机码错误: %s", in.S)
	}
	return in.D, nil
}
